#include <hidef.h>
#include "derivative.h"
#include "dac.h"

#define DAC_LD      0x40 // PM6 = LD/CS for DAC
#define SPTEF       0x20
#define SPIF        0x80
#define LOAD_DACA   0x90
#define LOAD_DACB   0xa0

void dac_init(void) {
  DDRM |= DAC_LD;   // Set PM6 to output.
  PTM  |= DAC_LD;   // Set PM6 high to deselect

  // Enable SPI0, Set Master Mode,
  SPI0CR1 = 0x50;

  SPI0CR2 = 2;

  /**
   * Set baud rate to 12Mhz @ 24Mz Bus speed
   * When 0 it will be bus clock/2
   */
  SPI0BR  = 0x00;

  WOMS    = 0;    // Port S Pull ups enabled  
  
}

void spi0_writeValue(byte data)
{
  while( !(SPI0SR & SPTEF) )  // Wait for done.
    ;

  SPI0DR = data;

  while( !(SPI0SR & SPIF) )
    ;

  data = SPI0DR;              // Reset the SPIF flag.
}

void dac_writeValue(byte data, byte channel) {
  /**
   * The output data to DAC is 16 bits:
   * A3|A2|A1|A0|D9|D8|D7|D6  D5|D4|D3|D2|D1|D0|xx|xx  xx= Don't care
   * A3-A0=Command  9=Load DAC A, 0xA=Load DAC B
   * We only use the upper 8 bits.
   */
  byte output_data;
  output_data = (channel == 0) ? LOAD_DACA : LOAD_DACB; // Set command
  output_data |= ((data >> 4) & 0xf);

  // Need to raise LD first.
  PTM |= DAC_LD;

  // Enable the chip for loading
  PTM &= ~DAC_LD;

  spi0_writeValue( output_data );
  output_data = (data <<4) & 0xf0;
  spi0_writeValue( output_data );
  PTM |= DAC_LD;
}